<template>
  <el-dialog 
    :model-value="modelValue" 
    @update:model-value="$emit('update:modelValue', $event)"
    :title="record ? '编辑休息记录' : '添加休息记录'"
    width="500px"
  >
    <el-form 
      :model="form" 
      :rules="rules" 
      ref="formRef"
      label-width="100px"
    >
      <el-form-item label="开始日期" prop="startDate">
        <el-date-picker
          v-model="form.startDate"
          type="date"
          placeholder="选择开始日期"
          style="width: 100%"
          :disabled-date="disabledStartDate"
          :disabled="dateRange && dateRange.type === 'start'"
        />
      </el-form-item>
      
      <el-form-item label="结束日期" prop="endDate">
        <el-date-picker
          v-model="form.endDate"
          type="date"
          placeholder="选择结束日期（可为空表示进行中）"
          style="width: 100%"
          :disabled-date="disabledEndDate"
          :disabled="dateRange && dateRange.type === 'end'"
          clearable
        />
      </el-form-item>
      
      <el-form-item label="描述" prop="description">
        <el-input
          v-model="form.description"
          type="textarea"
          :rows="3"
          placeholder="请输入休息描述"
          maxlength="200"
          show-word-limit
        />
      </el-form-item>
      
      <div class="form-tips">
        <p>💡 提示：</p>
        <ul>
          <li v-if="!dateRange">休息时间段的第一天和最后一天默认为车程时间</li>
          <li v-if="!dateRange">结束日期可以为空，表示当前正在休息中</li>
          <li v-if="!dateRange">结束日期不能超过今天</li>
          <li v-if="dateRange" class="date-range-tip">{{ dateRange.message }}</li>
          <li v-if="dateRange">必须与其他休息记录至少间隔1天工作时间</li>
        </ul>
      </div>
    </el-form>
    
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleCancel">取消</el-button>
        <el-button type="primary" @click="handleSave" :loading="loading">
          {{ loading ? '保存中...' : '保存' }}
        </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, reactive, watch } from 'vue'
import { ElMessage } from 'element-plus'

const props = defineProps({
  modelValue: {
    type: Boolean,
    default: false
  },
  record: {
    type: Object,
    default: null
  },
  selectedDate: {
    type: String,
    default: null
  },
  presetStartDate: {
    type: String,
    default: null
  },
  presetEndDate: {
    type: String,
    default: null
  },
  dateRange: {
    type: Object,
    default: null
  }
})

const emit = defineEmits(['update:modelValue', 'save'])

const formRef = ref()
const loading = ref(false)

const form = reactive({
  startDate: '',
  endDate: '',
  description: ''
})

const rules = {
  startDate: [
    { required: true, message: '请选择开始日期', trigger: 'change' }
  ],
  description: [
    { max: 200, message: '描述长度不能超过200个字符', trigger: 'blur' }
  ]
}

// 监听对话框打开，初始化表单
watch(() => props.modelValue, (newVal) => {
  if (newVal) {
    if (props.record) {
      // 编辑模式
      form.startDate = props.record.startDate
      form.endDate = props.record.endDate || ''
      form.description = props.record.description || ''
    } else {
      // 新增模式 - 根据预设类型决定初始化方式
      if (props.presetEndDate) {
        // 如果预设了结束日期，开始日期应该为空，让用户选择
        form.startDate = ''
        form.endDate = props.presetEndDate
      } else if (props.presetStartDate) {
        // 如果预设了开始日期，结束日期为空
        form.startDate = props.presetStartDate
        form.endDate = ''
      } else {
        // 默认情况：使用选中的日期作为开始日期
        form.startDate = props.selectedDate || ''
        form.endDate = ''
      }
      form.description = ''
    }
  }
})

// 禁用开始日期的逻辑
const disabledStartDate = (date) => {
  const today = new Date()
  today.setHours(23, 59, 59, 999)
  
  // 基本限制：不能超过今天
  if (date > today) return true
  
  // 如果有日期范围限制
  if (props.dateRange && props.dateRange.type === 'end') {
    const dateStr = formatDate(date)
    return dateStr < props.dateRange.minDate || dateStr > props.dateRange.maxDate
  }
  
  return false
}

// 禁用结束日期的逻辑
const disabledEndDate = (date) => {
  const today = new Date()
  today.setHours(23, 59, 59, 999)
  
  // 不能超过今天
  if (date > today) return true
  
  // 不能早于开始日期
  if (form.startDate && date < new Date(form.startDate)) return true
  
  // 如果有日期范围限制 - 当设置开始日期时，限制结束日期范围
  if (props.dateRange && props.dateRange.type === 'start') {
    const dateStr = formatDate(date)
    return dateStr < props.dateRange.minDate || dateStr > props.dateRange.maxDate
  }
  
  return false
}

const handleCancel = () => {
  emit('update:modelValue', false)
  resetForm()
}

const handleSave = async () => {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    loading.value = true
    
    const recordData = {
      startDate: formatDate(form.startDate),
      endDate: form.endDate ? formatDate(form.endDate) : null,
      description: form.description ? form.description.trim() : ''
    }
    
    emit('save', recordData)
    resetForm()
  } catch (error) {
    console.error('表单验证失败:', error)
  } finally {
    loading.value = false
  }
}

const resetForm = () => {
  if (formRef.value) {
    formRef.value.resetFields()
  }
  form.startDate = ''
  form.endDate = ''
  form.description = ''
}

const formatDate = (date) => {
  if (typeof date === 'string') return date
  if (date instanceof Date) {
    // 使用本地日期，避免时区问题
    const year = date.getFullYear()
    const month = String(date.getMonth() + 1).padStart(2, '0')
    const day = String(date.getDate()).padStart(2, '0')
    return `${year}-${month}-${day}`
  }
  return date
}
</script>

<style scoped>
.form-tips {
  margin-top: 16px;
  padding: 12px;
  background-color: #f8f9fa;
  border-radius: 6px;
  font-size: 13px;
  color: #666;
}

.form-tips p {
  margin-bottom: 8px;
  font-weight: 500;
}

.form-tips ul {
  margin: 0;
  padding-left: 20px;
}

.form-tips li {
  margin-bottom: 4px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

.date-range-tip {
  color: #e6a23c;
  font-weight: bold;
}
</style>
